package com.hyy.book2.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyy.book2.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

//统一数据返回格式
@ControllerAdvice
@Configuration
public class ResponseAdvice implements ResponseBodyAdvice{

    @Autowired
    private ObjectMapper objectMapper;

    @Override//说明是否支持统一返回格式
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        if(body instanceof Result<?>)return body;
        else if(body instanceof String){
            try {

                //把字符串封装成result对象，然后返回，注意是字符串类型
                return objectMapper.writeValueAsString(Result.success(body));

            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

        return Result.success(body);
    }
}
